package engine.ui.lite
{
	import com.greensock.TweenLite;
	
	import engine.control.MenuList;
	import engine.data.ModelLocator;
	import engine.display.guide.GuideLogic;
	import engine.event.SoundEvent;
	import engine.guide.GuideEvent;
	import engine.logic.LogSendLogic;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.newUi.ActionEctypeResultUI;
	import engine.newUi.ActionResultUI;
	import engine.newUi.ActorPropertyUI;
	import engine.newUi.CurrencyResultUI;
	import engine.newUi.DetailPropertyLogic;
	import engine.newUi.DetailPropertyUI;
	import engine.newUi.MyPropertyLogic;
	import engine.newUi.NoticeUI;
	import engine.newUi.NpcTalkUI;
	import engine.newUi.TopOtherPlayerUI;
	import engine.scene.SceneChangeManager;
	import engine.tip.TipsMainLogic;
	import engine.ui.UIManage;
	
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import newx.NxSprite;
	import newx.StageInfo;
	import newx.com.config.StaticIni;
	import newx.com.control.window.NxWindow;
	import newx.com.control.window.NxWindowDragType;
	
	public class BaseUI extends NxSprite
	{
		public static const LEFT : String = "left";
		public static const CENTER : String = "center";
		public static const RIGHT: String = "right";
		
		public		var created		:Boolean	=	false;
		
		/**是否创建过*/
		public		var inited		:Boolean	=	false;
		
		public 		var	layout		:String		=	"left";
		
		public		var windowBG	:NxWindow;
		
		public		var initPosX	:int	=	0;
		public		var initPosY	:int	=	0;
		
		private	var createdFunc	:Function;
		
		private	var onshowFunc	:Function;
		
		/**参数容器*/
		protected	var Properties	:Object;
		
		private 	var _space		:DisplayObjectContainer;
		
		private var currentSpace	:DisplayObjectContainer;
		
		//是否为可关闭窗口
		private	var _popupUI	:Boolean	=	true;
		
		//是否跟随舞台移动
		public 		var moveByScene		:Boolean	=	true;
		
		protected	var		_uiId	:int		=	0;
		
		private var _dragType:String;
		
		private 	var _model : ModelLocator;
			
		public function BaseUI(popupUI:Boolean=true)
		{
			_model		=	ModelLocator.getInstance();
			_popupUI	=	popupUI;
			Properties	=	new Object();
			super();			
		}
		
		public function showOrHide(space:DisplayObjectContainer = null , onshow:Function = null,...argc):void
		{
			if( created )
			{
				hide();
			}else
			{
//				updataUIPoint();
				show(space,onshow,argc);
			}
		}
		
		/**
		 *移去一个UI界面居中 
		 * @param ui
		 * 
		 */
		private function moveOneUI(ui:BaseUI):void
		{
			var w:int;
			var h:int;
			if( ui.windowBG != null )
			{
				w = ui.windowBG.width;
				h = ui.windowBG.height;
				
			}else
			{
				w = ui.width;
				h = ui.height;
			}
			if(ui.windowBG != null)
			{
				ui.windowBG.resetPoint();
				var point : Point;
				
				point  = ui.parent.globalToLocal( new Point( ( StageInfo.stage.stageWidth - w ) * .5, 
					( StageInfo.stage.stageHeight - h ) * .5 ) );
				TweenLite.to(ui,.3,{x:point.x,y:point.y});
			}
		}
		
		/**
		 *根据两个界面进行显示和移动 
		 * @param ui1 左边的UI
		 * @param ui2 右边的UI
		 * 
		 */
		private function towUIMove(ui1:BaseUI,ui2:BaseUI):void
		{
			var w1:int;
			var h1:int;
			var w2:int;
			var h2:int;

			if( ui1.windowBG != null )
			{
				w1 = ui1.windowBG.width;
				h1 = ui1.windowBG.height;
				
			}else
			{
				w1 = ui1.width;
				h1 = ui1.height;
			}
			if( ui2.windowBG != null )
			{
				w2 = ui2.windowBG.width;
				h2 = ui2.windowBG.height;
				
			}else
			{
				w2 = ui2.width;
				h2 = ui2.height;
			}
			ui1.windowBG.resetPoint();
			ui2.windowBG.resetPoint();
			var point : Point = ui1.parent.globalToLocal( new Point( ( StageInfo.stage.stageWidth -  (w1+w2)  ) * .5, 
				( StageInfo.stage.stageHeight - h1 ) * .5 ) );
			var point1 : Point = ui2.parent.globalToLocal( new Point( ( StageInfo.stage.stageWidth -  (w1+w2)  ) * .5, 
				( StageInfo.stage.stageHeight - h2 ) * .5 ) );
			TweenLite.to(ui1,.3,{x:point.x,y:point.y});
			TweenLite.to(ui2,.3,{x:point.x+ui1.width,y:point1.y});
		}
		
		/**
		 *把显示界面居中 
		 * 
		 */
		private function updataUIPoint():void
		{
			var id:int = UIManage.getInstance().getUIid(this);
			var allShowList:Array = StaticIni.getIniVar("allShowType","allShowList").split(",");
			if(allShowList.indexOf("UI_"+id)!=-1)
			{//不参于的界面直接显示
				return; 
			}
			this.layout = CENTER;
		}
		
		override public	function show(space:DisplayObjectContainer = null , onshow:Function = null,...argc):void
		{
			var id:int = UIManage.getInstance().getUIid(this);
			_space = space;
			LogSendLogic.getInstance().openUINum(this);
			this.mouseChildren = this.mouseEnabled = this.visible = true;
			if(this.parent == null){
				if(this.windowBG)
				{
					ModelLocator.getInstance().dispatchEvent(new SoundEvent(SoundEvent.UI_SHOW));
				}
			}
			BeforeShow();
			var addIndex:int	=	UIManage.getInstance()._uiArray.indexOf(this);
			
			var allBottomList:Array = StaticIni.getIniVar("allShowType","allBottomList").split(",");
			if(_popupUI){
				
				if(addIndex > -1 )
				{//如果该界面打开过,则将其排到最后。
					UIManage.getInstance()._uiArray.splice(addIndex,1);
				}

				UIManage.getInstance()._uiArray.push(this);
				
				while(UIManage.getInstance()._uiArray.length > UIManage._uiNo)
				{
					//如果超过最大显示界面数，则按先进先出的原则移除界面
					
					UIManage.getInstance().requestHideUI(
						(UIManage.getInstance()._uiArray.shift() as BaseUI)
						);
				}
			}
//			IO.traceLog(UIManage.getInstance()._uiArray.length  + "UI 界面在数量",this,"Class->",(this as Object).constructor);
			onshowFunc	=	onshow;
			if(!created)
			{
				if(_space == null)
				{
					_space	=	StageInfo.uiSpace;
				}
				this.addEventListener(Event.ADDED_TO_STAGE,onAddHandle);
				
				if(allBottomList.indexOf("UI_"+id)!=-1)
				{
					_space.addChildAt(this,0);
				}else
				{
					_space.addChild(this);
				}
				
				created	=	true;
				currentSpace = _space;
			}
			else
			{
				if(onshowFunc != null)
				{
					onshowFunc.call(this,this);
	 	
				}
				if(allBottomList.indexOf("UI_"+id)!=-1)
				{
					this.parent.setChildIndex(this,0);	
				}else
				{
					this.parent.setChildIndex(this,this.parent.numChildren-1);	
				}
//				this.parent.setChildIndex(this,this.parent.numChildren-1);		// 图层分布 防遮挡
			}
			
			modifyPostion();

			if(!_popupUI)return;
			if(this is ActorPropertyUI && (this as ActorPropertyUI).logicControl is MyPropertyLogic)
			{
				id = 1;
			}
			if(this is DetailPropertyUI && ((this as DetailPropertyUI).logicControl as DetailPropertyLogic).isOther )
			{
				id = 89;
			}
			if(argc[0] == 1 || argc[0] == 89)
			{
				id = argc[0];
			}
			//互拆的界面
			var showStr:String = StaticIni.getIniVar("allShowType","UI_"+id);
			//一直显示的界面
			var allShowList:Array = StaticIni.getIniVar("allShowType","allShowList").split(",");
			//强制靠右的界面
			var rigltList:Array = StaticIni.getIniVar("allShowType","rightList").split(",");
			var i:int = 0;
			var uiId:int = 0;
			var curUI:BaseUI;
			var allShowType:Array  = showStr.split(",");
//			
//			updataUIPoint();
			if(allShowList.indexOf("UI_"+id)!=-1)
			{//不参于的界面直接显示
//				show( space, onshow, argc );
				return; 
			}
			if(showStr == null || showStr =="")
			{//没有共享界面 关闭所有界面
				UIManage.getInstance().hideOtherOpendUI(null,id);
			}else
			{
				UIManage.getInstance().hideOtherOpendUI(showStr.split(","),id);
			}
			
			_model.dispatchEvent( new GuideEvent( GuideEvent.SHOW_UI, [ id ]) );
			
			for( i = 0;i<allShowType.length;i++)
			{
				var rightui:BaseUI;
				var leftui:BaseUI;
				uiId = int( allShowType[i].split("_")[1]);
				curUI = UIManage.getInstance().getUI(uiId);
				var thisid:String = "UI_"+UIManage.getInstance().getUIid(this);
				rightui = this;
				leftui = curUI;
				if(rigltList.indexOf(thisid)!=-1)
				{
					rightui = this;	
					leftui = curUI;
				}
				if(rigltList.indexOf("UI_"+uiId) != -1)
				{
					rightui = curUI
					leftui = this;
				}
				
				if(curUI!=null && curUI.visible)
				{
					if(allShowType[allShowType.length-1] != -1)
					{
						towUIMove(leftui,rightui);	
					}
					return;
				}
			}
		}
		
		private function offsizeY():int
		{
			var tHeight : int = StageInfo.stage.stageHeight;
			
			if(tHeight > StageInfo.rootMaxH)
			{
				tHeight	= StageInfo.rootMaxH;
			}
			else if(tHeight < StageInfo.rootH)
			{
				tHeight	=	StageInfo.rootH;
			}
			
			return (tHeight - StageInfo.rootH) >> 1
			
		}
		
		
		/**
		 *单纯关闭界面不参于其它逻辑 
		 * 
		 */
		public function hideCur():void
		{
			if(this is NpcTalkUI && this.created && null != GuideLogic.getInstance()._currGuideObj && 
				GuideLogic.getInstance()._currGuideObj.CoorTeam == "2")
			{
				/**关闭新手引导**/
				_model.dispatchEvent( new GuideEvent( GuideEvent.CLOSE_GUIDE,[] ));
			}
			this.mouseChildren = this.mouseEnabled = this.visible = false;
			if(this.parent !=null){
				if(this.windowBG)
				{
					ModelLocator.getInstance().dispatchEvent(new SoundEvent(SoundEvent.UI_HIDE));
				}
			}
			AfterHide();
			
			var addIndex:int	=	UIManage.getInstance()._uiArray.indexOf(this);
			
			//如果该界面打开过，则将其排到最后。
			if(addIndex > -1)
			{
				UIManage.getInstance()._uiArray.splice(addIndex,1);
			}
			
			if(parent != null)
			{
				removeEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
				parent.removeChild(this);
			}
			created	=	false;
			StageInfo.stage.focus = StageInfo.stage;
			
			TipsMainLogic.instance.hide();
			
			if( windowBG != null )
			{
				windowBG.resetPoint();
			}
		}
		
		override public	function hide():void
		{	
			if( !visible && !created )return;
			
			hideCur();
			var id:int = UIManage.getInstance().getUIid(this);
			if(this is ActorPropertyUI && (this as ActorPropertyUI).logicControl is MyPropertyLogic)
			{
				id = 1;
			}
			if(this is DetailPropertyUI && ((this as DetailPropertyUI).logicControl as DetailPropertyLogic).isOther)
			{
				id = 89;
			}
			
			_model.dispatchEvent( new GuideEvent( GuideEvent.HIDE_UI, [ id ]) );
			//			if(argc[0] == 1)
			//			{
			//				id = 1;
			//			}
			var showStr:String = StaticIni.getIniVar("allShowType","UI_"+id);
			var allShowList:Array = StaticIni.getIniVar("allShowType","allShowList").split(",");
			var rigltList:Array = StaticIni.getIniVar("allShowType","rightList").split(",");
			var i:int = 0;
			var uiId:int = 0;
			var curUI:BaseUI;
			var allShowType:Array  = showStr.split(",");
//			if( created )
//			{
				for(i = 0;i<allShowType.length;i++)
				{
					uiId = int( allShowType[i].split("_")[1]);
					curUI = UIManage.getInstance().getUI(uiId);
					
					if(curUI!=null && curUI.visible)
					{
						moveOneUI(UIManage.getInstance().getUI(uiId));
						return;
					}
				}
//			}
			
				
				if(this is TopOtherPlayerUI)
				{
					StageInfo.stage.dispatchEvent(new Event(Event.RESIZE));
				}
		}
		
		/**取得属性*/
		public final function GetProperties(PropertiesName : String):*
		{
			if (CheckProperties(PropertiesName))
			{
				return this.Properties[PropertiesName];
			}
			else
			{
//				throw new Error("[BaseControl::GetProperties]指定参数不存在！");
				return null;
			}
		}
		
		/**设置属性*/		
		public final function HandleProperties(PropertiesName:String, PropertiesValue:*):void
		{
			this.Properties[PropertiesName] = PropertiesValue;
		}
		
		/**删除属性*/
		public final function DeleteProperties(PropertiesName : String):void
		{
			if (this.Properties.hasOwnProperty(PropertiesName) == true)
			{
				delete this.Properties[PropertiesName];
			}
			else
			{
				//throw new Error("[BaseObject::DeleteProperties]指定参数不存在！");
			}
		}
		
		public final function clearProperties():void
		{
			Properties	=	new Object();
		}
		
		/**检测属性是否存在*/
		public final function CheckProperties(PropertiesName : String):Boolean
		{
			return this.Properties.hasOwnProperty(PropertiesName)
		}
		
		public function getDataForEach(func:Function):void
		{
			for(var p:String in this.Properties)
			{
				func.call(this,p,GetProperties(p));
			}
		}
		
		public function Init():void
		{
			
			
		}
		
		protected function onAdd():void
		{
			
		}
		
		private function onCreatComplete(...argc):void
		{
			dispatchEvent(new Event(Event.COMPLETE));
			// 完成显示初始化后，进行逻辑初始化
			Init()
			createdFunc.call(this);
		}
		
		private function onAddHandle(e:Event):void
		{
			addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
			root.stage.addEventListener(MouseEvent.MOUSE_UP,onMouseUP);
			removeEventListener(Event.ADDED_TO_STAGE,onAddHandle);			
			if(onshowFunc != null)
			{
				onshowFunc.call(this,this);
			}
			onAdd();
		}
		
		private function onMouseDown(e:MouseEvent):void
		{
			MenuList.hide();
			var uiid:int = UIManage.getInstance().getUIid(this);
			var idList:Array = StaticIni.getIniVar("allShowType","allDownList").split(",");
			if(idList.indexOf("UI_"+uiid)!=-1)
			{
				return;
			}
			if(_popupUI)
			{
				UIManage.getInstance().setUIMask(this.parent);
				this.parent.setChildIndex(this,this.parent.numChildren-1);
			}
		}
		
		private function onMouseUP(e:MouseEvent):void
		{
			UIManage.getInstance().cancelUIMask();
		}
		
		protected	function	BeforeShow():void
		{
			if( this is ActionEctypeResultUI || this is ActionResultUI || this is CurrencyResultUI )
			{//战斗结算界面
				layout = CENTER;
				
				_space = StageInfo.attackSpace;
			}
		}
		
		protected	function	AfterHide():void
		{
			
		}
		
		public	function beforeShow():void
		{
			BeforeShow();
		}
		
		public	function afterHide():void
		{
			AfterHide();
		}
		
		public function forbidDrag():void
		{
			if(null		!=	windowBG)
			{
//				_dragType=windowBG.dragSpaceType;
				windowBG.dragSpaceType	=	NxWindowDragType.Window_NONE;
			}
		}
		
		public function restoreDrag():void
		{
			if(null		!=	windowBG)
				windowBG.dragSpaceType	=	NxWindowDragType.Window_TITLE;
		}
		
		
		/**修正在舞台上的位置*/
		public function modifyPostion():void
		{
			NoticeUI.getInstance().updataView();
			if(windowBG!=null)
			{
				windowBG.resetPoint();
			}
			if( layout == RIGHT )
			{//界面需要靠右边界显示
				x = SceneChangeManager.getGameWidth() - width - initPosX + SceneChangeManager.getGameX();
				y = initPosY;
			}else if( layout == CENTER )	
			{
				var w:int;
				var h:int;
				if( this.windowBG != null )
				{
					w = this.windowBG.width;
					h = this.windowBG.height;
				}else
				{
					w = this.width;
					h = this.height;
				}
					var point : Point = parent.globalToLocal( new Point( ( StageInfo.stage.stageWidth - w ) * .5,
						( StageInfo.stage.stageHeight - h ) * .5 ) );
					x = point.x;
					y = point.y;
			}else
			{
				if(windowBG!=null)
				{
					windowBG.x	=	initPosX;
					windowBG.y	=	moveByScene ? initPosY - offsizeY() : initPosY;
					x	=	0;
					y	=	0;
				}
				else
				{
					x		=	initPosX;
					y		=	moveByScene ? initPosY - offsizeY() : initPosY;
				}
			}
		}
		
		protected function requestClose():void
		{
			if(	_uiId	<=	0	)
			{
				_uiId	=	UIManage.getInstance().getUIid(this);
			}
			
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_REQUEST_CLOSE_UI,_uiId);
		}
	}
}